package com.demo.drls.controller;

import com.demo.drls.model.AccountingRuleDto;
import com.demo.drls.model.Address;
import com.demo.drls.model.Product;
import com.demo.drls.model.fact.AddressCheckResult;
import lombok.extern.slf4j.Slf4j;
import org.drools.decisiontable.InputType;
import org.drools.decisiontable.SpreadsheetCompiler;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.utils.KieHelper;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

/**
 *
 * @author
 * @since
 */
@RestController
@RequestMapping("/test")
@Slf4j
public class TestController {

  @Resource
  private KieContainer kieContainer;

  @ResponseBody
  @GetMapping("/address/{num}")
  public String test(@PathVariable("num") int num){
    Address address = new Address();
    address.setPostcode(generateRandom(num));
    KieSession kieSession = kieContainer.newKieSession();

    AddressCheckResult result = new AddressCheckResult();
    kieSession.insert(address);
    kieSession.insert(result);
    int ruleFiredCount = kieSession.fireAllRules();
    kieSession.destroy();
    log.info( "触发了" + ruleFiredCount + "条规则");

    if (result.isPostCodeResult()) {
      return  "规则校验通过";
    } else {
      return  "规则校验失败";
    }

  }


  /**
   * 生成随机数
   * @param num
   * @return
   */
  public String generateRandom(int num) {
    String chars = "0123456789";
    StringBuffer number = new StringBuffer();
    for (int i = 0; i < num; i++) {
      int rand = (int) (Math.random() * 10);
      number = number.append(chars.charAt(rand));
    }
    return number.toString();
  }


  @ResponseBody
  @GetMapping("/product/{prdClass}/{prdSubclass}")
  public String testProduct(@PathVariable("prdClass") String prdClass, @PathVariable("prdSubclass") String prdSubclass){
    Product input = new Product();
    input.setInProductCategory(prdClass);
    input.setInProductSubclass(prdSubclass);
    KieSession kieSession = kieContainer.newKieSession();
    kieSession.insert(input);
    int ruleFiredCount = kieSession.fireAllRules();
    kieSession.destroy();
    log.info( "触发了" + ruleFiredCount + "条规则");

    return input.getOutConsumerType() == null ? "没有匹配到结果" : input.getOutConsumerType();

  }


  @ResponseBody
  @GetMapping("/decideTable/{prdClass}/{prdSubclass}")
  public String testDecideTable(@PathVariable("prdClass") String prdClass,
                                @PathVariable("prdSubclass") String prdSubclass) throws IOException {
    //get drl
    org.springframework.core.io.Resource[] resources = getRuleFiles();
    File file = Arrays.asList(resources).stream()
        .filter(resource -> "Sample.xls".equals(resource.getFilename()))
        .findFirst()
        .get()
        .getFile();
    InputStream is = new FileInputStream(file);
    SpreadsheetCompiler compiler = new SpreadsheetCompiler();
    String drl = compiler.compile(is, InputType.XLS);
    log.info("{}",drl);
    //build input
    Product input = new Product();
    input.setInProductCategory(prdClass);
    input.setInProductSubclass(prdSubclass);
    //build kieSession
    KieHelper kieHelper = new KieHelper();
    kieHelper.addContent(drl, ResourceType.DRL);
    KieSession kieSession = kieHelper.build().newKieSession();
    //get result
    kieSession.insert(input);
    int ruleFiredCount = kieSession.fireAllRules();
    kieSession.destroy();
    log.info( "触发了" + ruleFiredCount + "条规则");

    return input.getOutConsumerType() == null ? "没有匹配到结果" : input.getOutConsumerType();

  }

  @PostMapping("/kjrule")
  public String testKjrule(@RequestBody AccountingRuleDto accountingRuleDto) throws IOException {
    //get drl
    log.info("start");
    org.springframework.core.io.Resource[] resources = getRuleFiles();
    File file = Arrays.asList(resources).stream()
            .filter(resource -> "kjrule.xls".equals(resource.getFilename()))
            .findFirst()
            .get()
            .getFile();
    InputStream is = new FileInputStream(file);
    SpreadsheetCompiler compiler = new SpreadsheetCompiler();
    String drl = compiler.compile(is, InputType.XLS);
    log.info("{}",drl);
    //build input

    //build kieSession
    KieHelper kieHelper = new KieHelper();
    kieHelper.addContent(drl, ResourceType.DRL);
    KieSession kieSession = kieHelper.build().newKieSession();
    //get result
    kieSession.insert(accountingRuleDto);
    int ruleFiredCount = kieSession.fireAllRules();
    kieSession.destroy();
    log.info( "触发了" + ruleFiredCount + "条规则");

    return accountingRuleDto.toString();

  }

  private org.springframework.core.io.Resource[] getRuleFiles() throws IOException {
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    return resourcePatternResolver.getResources("classpath*:decideTables/**/*.*");
  }


}
